package com.cincc.cincc_pbx.ui;

import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentTransaction;

import com.cincc.cincc_pbx.R;
import com.cincc.cincc_pbx.common.CallUtil;
import com.cincc.cincc_pbx.common.OkHttpUtils;
import com.cincc.cincc_pbx.constant.CallConstant;
import com.cincc.cincc_pbx.model.EventBusModel;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationBarView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

public class MainActivity extends BaseActivity implements NavigationBarView.OnItemSelectedListener, View.OnClickListener {
    private static final String TAG = "MainActivity";

    @Override
    protected int contentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void afterViews() {
        super.afterViews();
        initView();
        getUserAndExtension();
    }

    private void getUserAndExtension() {
        try {
            JSONObject param = new JSONObject();

            JSONObject pageJson = new JSONObject();
            pageJson.put("pageNum", 1);
            pageJson.put("pageSize", 100);

            JSONArray jsonArray = new JSONArray();
            JSONObject tenantIdJson = new JSONObject();
            tenantIdJson.put("key", "tenantId");
            tenantIdJson.put("value", CallConstant.loginModel.getVccId());

            JSONObject accountJson = new JSONObject();
            accountJson.put("key", "account");
            accountJson.put("value", CallConstant.loginModel.getUserName());

            jsonArray.put(tenantIdJson);
            jsonArray.put(accountJson);

            param.put("page", pageJson);
            param.put("parameters", jsonArray);

            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "Bearer " + CallConstant.loginModel.getAccessToken());
            OkHttpUtils.httpPost(CallConstant.REQUEST_MY_INFO_URL, param.toString(), header, new OkHttpUtils.ICallBack() {
                @Override
                public void onSuccessful(Call call, String data) {
                    Log.e(TAG, "getMyInfo onSuccessful: " + data);
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if (jsonObject.getString("rtnCode").equals("0000")) {
                            if (jsonObject.getJSONObject("data").optJSONArray("dataResult") != null) {
                                JSONObject userJson = jsonObject.getJSONObject("data").optJSONArray("dataResult").getJSONObject(0);
                                String userId = userJson.getString("id");
                                CallConstant.loginModel.setUserId(userId);
                                Log.e(TAG, "onSuccessful: set user id  is " + userId);

                                JSONObject extend = new JSONObject(userJson.getString("extend04"));
                                String telPhone = extend.getJSONObject("params").getString("telephoneNumber");
                                CallConstant.loginModel.setTelPhone(telPhone);
                                EventBus.getDefault().post(new EventBusModel(CallConstant.REFRESH_RECORD_EVENT, null));
                                Log.e(TAG, "onSuccessful: telPhone is " + telPhone);
                                getExtensionInfo(telPhone);
                            }
                        }
                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }

                @Override
                public void onFailure(Call call, String errorMsg) {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_SHORT).show());
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "getMyInfo: " + e.getMessage());
            runOnUiThread(() -> Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }

    private void getExtensionInfo(String telPhone) {
        try {
            String vccId = CallConstant.loginModel.getVccId();
            JSONObject params = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("vccId", vccId);
            jsonObject.put("telephoneNumber", telPhone);
            params.put("params", jsonObject);
            Log.e(TAG, "getExtensionInfo:params is " + params);
            Map<String, String> header = new HashMap<>();
            header.put("Authorization", "Bearer " + CallConstant.loginModel.getAccessToken());
            OkHttpUtils.httpPost(CallConstant.REQUEST_GET_EXTENSION_URL, params.toString(), header, new OkHttpUtils.ICallBack() {
                @Override
                public void onSuccessful(Call call, String data) {
                    Log.e(TAG, "getExtensionInfo onSuccessful: " + data);
                    try {
                        JSONObject jsonObject = new JSONObject(data);
                        if (jsonObject.getString("rtnCode").equals("0000")) {
                            String passwd = jsonObject.getJSONObject("data").getString("passwd");
                            CallConstant.loginModel.setPasswd(passwd);
                            runOnUiThread(() -> CallUtil.getInstance().register(MainActivity.this));
                        }
                    } catch (Exception e) {
                        runOnUiThread(() -> Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                }

                @Override
                public void onFailure(Call call, String errorMsg) {
                    Log.e(TAG, "getExtensionInfo onFailure: " + errorMsg);
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, errorMsg, Toast.LENGTH_SHORT).show());
                }
            });
        } catch (Exception e) {
            Log.e(TAG, "getExtensionInfo: " + e.getMessage());
            runOnUiThread(() -> Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show());
        }
    }

    BottomNavigationView bottomNavigationView;


    private void initView() {
        bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnItemSelectedListener(this);
        showHomePage();
    }

    private HomeFragment homeFragment;
    private ContactFragment contactFragment;
    private DialFragment dialFragment;
    private MineFragment mineFragment;

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_1:
                showHomePage();
                return true;
            case R.id.navigation_2:
                showContactPage();
                return true;
            case R.id.navigation_3:
                showDialPage();
                return true;
            case R.id.navigation_4:
                showMinePage();
                return true;
        }
        return false;
    }

    private void showHomePage() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        if (homeFragment == null) {
            homeFragment = new HomeFragment();
            fragmentTransaction.add(R.id.nav_host_fragment, homeFragment);
        } else {
            fragmentTransaction.show(homeFragment);
        }
        fragmentTransaction.commit();
    }

    private void showContactPage() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        if (contactFragment == null) {
            contactFragment = new ContactFragment();
            fragmentTransaction.add(R.id.nav_host_fragment, contactFragment);
        } else {
            fragmentTransaction.show(contactFragment);
        }
        fragmentTransaction.commit();
    }

    private void showDialPage() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        if (dialFragment == null) {
            dialFragment = new DialFragment();
            fragmentTransaction.add(R.id.nav_host_fragment, dialFragment);
        } else {
            fragmentTransaction.show(dialFragment);
        }
        fragmentTransaction.commit();
    }

    private void showMinePage() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideFragment(fragmentTransaction);
        if (mineFragment == null) {
            mineFragment = new MineFragment();
            fragmentTransaction.add(R.id.nav_host_fragment, mineFragment);
        } else {
            fragmentTransaction.show(mineFragment);
        }
        fragmentTransaction.commit();
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        if (homeFragment != null) {
            fragmentTransaction.hide(homeFragment);
        }
        if (contactFragment != null) {
            fragmentTransaction.hide(contactFragment);
        }
        if (dialFragment != null) {
            fragmentTransaction.hide(dialFragment);
        }
        if (mineFragment != null) {
            fragmentTransaction.hide(mineFragment);
        }
    }

    private static final long DOUBLE_CLICK_TIME_DELTA = 2000; // 两次返回键按下的最大时间间隔，单位为毫秒
    private boolean isBackPressedOnce = false; // 是否已经按下一次返回键
    private long lastBackPressedTime = 0; // 上次按下返回键的时间

    @Override
    public void onBackPressed() {
        // 判断是否是第一次按下返回键
        if (!isBackPressedOnce) {
            // 记录当前时间
            lastBackPressedTime = System.currentTimeMillis();
            isBackPressedOnce = true;
            Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
        } else {
            // 获取当前时间
            long currentBackPressedTime = System.currentTimeMillis();
            // 判断两次按下的时间间隔是否小于规定的时间
            if (currentBackPressedTime - lastBackPressedTime <= DOUBLE_CLICK_TIME_DELTA) {
                // 退出应用
                finish();
            } else {
                // 重置计时器
                isBackPressedOnce = false;
                Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
            }
        }
    }
}